package tau.pimpmyfreedb.GUI;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;

import tau.facebook.FacebookBrowser;
import tau.facebook.LoginCompleteListener;
import tau.pimpmyfreedb.master.Callback;

/**
 * Facebook login window
 */
public class FacebookLoginWindow implements LoginCompleteListener {
  private final Shell shell;
  private Callback<FacebookBrowser> callback = null;

  public FacebookLoginWindow(Shell parent) {
    shell = createShell(parent);
  }

  private Shell createShell(Shell parent) {

    // shell	  
    final Shell shell = SWTUtil.getShell(parent);
    shell.setText("Facebook Login");
    Rectangle monitor_bounds = shell.getMonitor().getBounds();
    shell.setSize(new Point(monitor_bounds.width * 2 / 3,
        monitor_bounds.height * 2 / 3));
    shell.setLayout(new GridLayout(1, true));

    // composite
    Composite composite = new Composite(shell, SWT.NONE);
    GridData gridData = new GridData(shell.getSize().x - 20,
        shell.getSize().y - 60);
    composite.setLayout(new GridLayout(1, true));
    composite.setLayoutData(gridData);

    // browser
    FacebookBrowser fbBrowser = new FacebookBrowser(shell, composite, gridData);
    fbBrowser.addLoginListener(this);
    fbBrowser.gotoLoginPage();

    return shell;
  }

  public Shell getShell() {
    return shell;
  }

  public void setOnLoginComplete(Callback<FacebookBrowser> callback) {
    this.callback = callback;
  }

  @Override
  public void onLoginComplete(FacebookBrowser sender) {
    if (callback != null) {
      callback.execute(sender);
      shell.setSize(shell.getSize().x / 2, shell.getSize().y / 2);
      shell.setLocation(shell.getLocation().x, shell.getLocation().y + shell.getSize().y);
    }
  }
}
